/*
 * ProfileKeysView.java
 *
 * Created on 12 Kasım 2008 Çarşamba, 12:50
 */
package org.testis.gui.mvc.view.labels;

import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.controller.testdesign.LabelSettingsController;
import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.view.labels.DefaultLabelJTree;
import org.testis.orm.labelhandler.LabelRefined;
import org.testis.utils.tree.DefaultMutableLabelNode;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author  nurhat
 */
public class LabelSettingsView extends AtofBaseDialog implements
        AbstractViewPanel {

    private LabelSettingsController m_controller = null;
    private DefaultMutableLabelNode m_treeRoot = null;

    public LabelSettingsView(Frame owner, boolean modal) {
        super(owner, modal);
        m_controller = TestDesignControllerList.newInstance().getLabelSettingsController();
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("/*unchecked*/")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        labelTree = new DefaultLabelJTree();
        btnEdit = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Global Label Names");
        setMinimumSize(new java.awt.Dimension(320, 320));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        labelTree.setModel(new DefaultTreeModel(null));
        labelTree.setAutoscrolls(true);
        labelTree.setEditable(true);
        labelTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelTreeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(labelTree);

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnExit)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnExit});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDelete)
                    .addComponent(btnAdd)
                    .addComponent(btnEdit)
                    .addComponent(btnExit))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    WindowListener[] listeners = getWindowListeners();
    for (int i = 0; i
            < listeners.length; i++) {
        this.removeWindowListener(listeners[i]);
    }
    m_controller.operationCloseWindow();
}//GEN-LAST:event_formWindowClosed

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
    dispose();
}//GEN-LAST:event_btnExitActionPerformed

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    DefaultMutableLabelNode selectedNode = ((DefaultLabelJTree) labelTree).getSelectedNode();
    if (confirmDelete(selectedNode)) {
        m_controller.operationDeleteLabel(selectedNode);
    }
}//GEN-LAST:event_btnDeleteActionPerformed

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
    String labelName = JOptionPane.showInputDialog("Enter Label Name:");
    if (labelName == null || labelName.isEmpty()) {
        return;
    }
    DefaultMutableLabelNode selectedNode = ((DefaultLabelJTree) labelTree).getSelectedNode();
    addLabel(selectedNode, labelName);
}//GEN-LAST:event_btnAddActionPerformed

private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
    DefaultMutableLabelNode selectedNode = ((DefaultLabelJTree) labelTree).getSelectedNode();
    if (selectedNode != null && selectedNode.getLabel() != null) {
        LabelRefined selectedLabel = selectedNode.getLabel();
        String labelName = JOptionPane.showInputDialog("Enter Label Name:",
                selectedLabel.getName());
        if (labelName == null || labelName.isEmpty()) {
            return;
        }
        m_controller.operationSaveLabel(selectedLabel.getId(), labelName);
    }
}//GEN-LAST:event_btnEditActionPerformed
    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                LabelSettingsController.SHOW_VIEW_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.TREE_LOAD_PROPERTY)) {
            DefaultMutableLabelNode root = (DefaultMutableLabelNode) evt.getNewValue();
            m_treeRoot = root;
            loadTree(root);
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.TREE_REFRESH_PROPERTY)) {
            labelTree.updateUI();
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.SELECTION_TREE_PATH_PROPERTY)) {
            TreePath path = (TreePath) evt.getNewValue();
            setSelectionTreePath(path);
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

//    private DefaultMutableLabelNode getSelectedNode() {
//        DefaultMutableLabelNode currentNode = null;
//        TreePath currentSelection = labelTree.getSelectionPath();
//        if (currentSelection != null) {
//            currentNode = (DefaultMutableLabelNode) (currentSelection.getLastPathComponent());
//        }
//        return currentNode;
//    }
    private void addLabel(DefaultMutableLabelNode selectedNode, String name) {
        LabelRefined containerLabel = null;
        if (selectedNode != null) {
            containerLabel = selectedNode.getLabel();
        }
        int containerId = 0;
        if (containerLabel != null) {
            containerId = containerLabel.getId();
        }
        m_controller.operationAddLabel(name, containerId);
    }

    private boolean confirmDelete(DefaultMutableLabelNode selectedNode) {
        if (selectedNode == null) {
            return false;
        }
        LabelRefined label = selectedNode.getLabel();
        if (label == null) {
            return false;
        }
        boolean confirmForDelete = false;
        int result = javax.swing.JOptionPane.showConfirmDialog(null,
                "Are you sure you want to delete this label?",
                "Delete Confirmation",
                javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                javax.swing.JOptionPane.QUESTION_MESSAGE);
        if (result == javax.swing.JOptionPane.YES_OPTION) {
            confirmForDelete = true;
            if (TestDesignControllerList.newInstance().getLabelSettingsController().
                    operationCheckIsInUse(label.getId())) {
                result = javax.swing.JOptionPane.showConfirmDialog(null,
                        "This label is in use! Are you sure you want to delete this label?",
                        "Delete Confirmation",
                        javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                        javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result == javax.swing.JOptionPane.YES_OPTION) {
                    confirmForDelete = true;
                } else {
                    confirmForDelete = false;
                }
            }
        }
        return confirmForDelete;
    }

    private void setSelectionTreePath(TreePath path) {
        if (path != null) {
            labelTree.setSelectionPath(path);
        }
    }

    private void loadTree(DefaultMutableLabelNode root) {
        ((DefaultLabelJTree) labelTree).loadLabels(root);
//        if (root == null) {
//            return;
//        }
//        DefaultTreeModel treeModel = new DefaultTreeModel(root);
//        labelTree.setModel(treeModel);
//        labelTree.updateUI();
//        expandTree();
    }

    private void expandTree() {
        for (int i = 0; i < labelTree.getRowCount(); i++) {
            labelTree.expandRow(i);
        }
    }

private void labelTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelTreeMouseClicked
    TreePath path = labelTree.getPathForLocation(evt.getX(),
            evt.getY());
    labelTree.setSelectionPath(path);
    DefaultMutableLabelNode selectedNode = ((DefaultLabelJTree) labelTree).getSelectedNode();
    if (selectedNode != null) {
        m_controller.operationSelectLabel(selectedNode);
    }
}//GEN-LAST:event_labelTreeMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnExit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree labelTree;
    // End of variables declaration//GEN-END:variables

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TestDesignControllerList.newInstance().getLabelSettingsController().operationStartLoader();
            }
        });
    }
}
